<script setup lang="ts">
import AMapLoader from '@amap/amap-jsapi-loader';
import {Plus, Search} from "@element-plus/icons-vue";
import {ref, onUpdated, onBeforeUpdate} from "vue";
import {useRoute, useRouter,} from 'vue-router'
import axios from "axios";
import {loginUser, ServerHost} from "@/main";
import {ElNotification} from "element-plus";
import PostOrEditGoods from "@/components/goodsManage/PostOrEditGoods.vue";
import PostOrEditAgritainment from "@/components/agritainmentManage/PostOrEditAgritainment.vue";
import {downloadImg} from "@/utils";

const router = useRouter()
const route = useRoute()


let map = null
let markerList = []
let markerTextList = []
let AMap = null
AMapLoader.load({
  key: "225ab1a1758d7eed67798492e1c6263e",
  version: "2.0",
  plugins: [
    "AMap.Geolocation",
  ],
}).then((mAMap) => {
  const position = [102.579012, 33.868706]
  AMap = mAMap
  map = new AMap.Map('map', {
    center: position,
    zoom: 4,
  });
  map.addControl(new AMap.Geolocation());
  loadList()
}).catch(e => {
  console.log(e);
})

const searchKey = ref("")

const agritainmentList = ref([])
const hasLoad = ref(false)
const isLoadingList = ref(false)
const loadList = () => {
  console.log("开始获取政策列表")
  axios.get(`${ServerHost}/getAgritainmentList?key=${searchKey.value}`)
      .then((res) => {
        if (res.status === 200) {
          agritainmentList.value = res.data;
          hasLoad.value = true
          isLoadingList.value = false
          markerList = []
          markerTextList = []
          markerList.forEach(marker => {
            map.remove(marker)
          })
          markerTextList.forEach(text => {
            text.remove(map)
          })
          agritainmentList.value.forEach((item) => {
            const marker = new AMap.Marker({
              position: [item.lng, item.lat],
            })
            marker.on("click", (e) => {
              console.log(111)
              // 跳转到农家乐详细页
              const url = router.resolve({
                path: `/agritainment/${item.id}`,
              });
              window.open(url.href);
            })
            map.add(marker)
            markerList.push(marker)
            const text = new AMap.Text({
              text: item.name, //标记显示的文本内容
              anchor: "bottom-center", //设置文本标记锚点位置
              cursor: "pointer", //指定鼠标悬停时的鼠标样式。
              offset: [0, -36],
              position: [item.lng, item.lat],
            });
            text.setMap(map); //将文本标记设置到地图上
            markerTextList.push(text)
          })
        } else {
          ElNotification({
            title: '政策获取失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

// 懒加载农家乐图片
const goodsImgItemRefs = ref([]);
const setGoodsImgRef = (el: any) => {
  if (el) {
    goodsImgItemRefs.value.push(el);
  }
}

onBeforeUpdate(() => {
  goodsImgItemRefs.value = [];
});

const goodHasLoadImgIdList = ref([]); // 已经加载过图片的商品id列表
onUpdated(() => {
  goodsImgItemRefs.value.forEach((item: any) => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const goodId = item.getAttribute('data-id');
          if (!goodHasLoadImgIdList.value.includes(goodId)) {
            goodHasLoadImgIdList.value.push(goodId);
            const goods = agritainmentList.value.find(goods => goods.id == goodId)
            //   加载图片
            downloadImg(goods.img, "agritainmentImg/")
                .then(res => {
                  if (res.status === 200) {
                    const type = 'image/png'
                    const blob = new Blob([res.data], {type: type})
                    const imgFile = new File([blob], goods.img, {type: type})
                    goods.imgUrl = URL.createObjectURL(imgFile)
                    console.log(goods)
                  }
                })
          }

        }
      });
    });
    observer.observe(item);
  });
});

const onSearchKeydown = (event: KeyboardEvent) => {
  if (event.key === "Enter") {
    onSearch()
  }
}

const onSearch = () => {
  if (searchKey.value !== "") {
    loadList()
  }
}

const onClearSearch = (id: string) => {
  loadList()
}

const postOrEditGoodsDialogVisible = ref(false)
const onAddAgritainment = async () => {
  console.log("添加农家乐")
  postOrEditGoodsDialogVisible.value = true
}
</script>

<template>
  <el-card class="m-2">
    <div class="flex flex-col gap-1.5">
      <el-input type="text" v-model="searchKey" @keydown="onSearchKeydown" class="mb-2" placeholder="搜索农家乐"
                :prefix-icon="Search" clearable @clear="onClearSearch">
        <template #append>
          <el-button :icon="Search" @click="onSearch"/>
        </template>
      </el-input>
      <div id="map" class="m-auto"/>
    </div>
  </el-card>

  <!-- 农家乐列表 -->
  <p class="m-2">最新农家乐</p>
  <div class="agritainment-list m-2">
    <div v-for="agritainment in agritainmentList" :ref="setGoodsImgRef" :data-id="agritainment.id">
      <el-card>
        <router-link :to="'/agritainment/' + agritainment.id" target="_blank">
          <div>
            <div class="goods-item-img-div mb-1">
              <img class="good-item-img" :src="agritainment.imgUrl" alt="Img"/>
            </div>
          </div>
          <p>{{ agritainment.name }}</p>
        </router-link>
      </el-card>
    </div>

  </div>

  <!-- 固定在右下角的添加农家乐按钮 -->
  <el-tooltip
      v-if="loginUser != null && (loginUser.username === 'rrsRoot')"
      class="add-goods-tooltip"
      content="上架农家乐"
      placement="top">
    <el-button class="add-agritainment-bt" circle @click="onAddAgritainment">
      <template #icon>
        <el-icon :size="20">
          <Plus/>
        </el-icon>
      </template>
    </el-button>
  </el-tooltip>

  <!-- 添加农家乐 Dialog-->
  <el-dialog
      v-model="postOrEditGoodsDialogVisible"
      title="添加农家乐">
    <PostOrEditAgritainment type="new"/>
  </el-dialog>
</template>

<style scoped lang="scss">
#map {
  width: 100%;
  max-width: 900px;
  aspect-ratio: 16/9;
  border-radius: 4px;
}

.add-agritainment-bt {
  width: 60px;
  height: 60px;
  position: fixed;
  right: 80px;
  bottom: 80px;
}

.agritainment-list {
  margin: auto;
  max-width: 900px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
}

.goods-item-img-div {
  aspect-ratio: 1;
}

.good-item-img {
  width: 100%;
  height: 100%;
  border-radius: 2px;
  object-fit: cover;
}
</style>
